<template>
  <el-space direction="vertical">
    <el-form
      ref="userLoginDtoRef"
      label-position="top"
      label-width="auto"
      :model="userLoginDto"
      style="width: 400px">
      <el-form-item label="用户名" prop="username">
        <el-input v-model="userLoginDto.username" />
      </el-form-item>
      <el-form-item label="密码" prop="password">
        <el-input v-model="userLoginDto.password" type="password" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" @click="doLogin(userLoginDtoRef)">
          Login
        </el-button>
        <el-button type="danger" @click="doLogout(userLoginDtoRef)">
          Logout
        </el-button>
        <el-button @click="doReset(userLoginDtoRef)">Reset</el-button>
      </el-form-item>
    </el-form>

    <el-card style="width: 400px">
      <template #header>
        <div class="card-header">
          <span>登录Token</span>
        </div>
      </template>
      <p style="word-wrap: break-word">
        {{ userStore?.token ?? null }}
      </p>
    </el-card>
  </el-space>
</template>

<script lang="ts" setup>
// 全局状态-user
import { useUserStore } from "@/store";
import { UserLoginDto } from "@/api";
import { reactive, ref } from "vue";
import { FormInstance } from "element-plus";
import { login, logout } from "@/hooks/userAccount.ts";
import { useMessage } from "naive-ui";

const message = useMessage();
const userStore = useUserStore();
const userLoginDtoRef = ref<FormInstance>();
const userLoginDto = reactive<UserLoginDto>({
  username: "user2#2",
  password: "123123",
});

const doLogin = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  const { code, msg } = await login(userLoginDto);
  if (code === 100) {
    message.success(msg as string);
  } else {
    message.error(msg as string);
  }
};

const doLogout = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  const { code, msg } = await logout();
  if (code === 100) {
    message.success(msg as string);
  } else {
    message.error(msg as string);
  }
};

const doReset = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};
</script>

<style scoped></style>
